const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();

//get-login
router.use('/static', express.static(path.resolve(__dirname, '../static')));
router.get('/login', (req, res) => {
    res.sendFile(path.resolve(__dirname, '../views/login.html'));
});

// 接收前端的json对象
router.use(express.urlencoded({
    extended: false
}))
//post login
router.post('/login', (req, res, next) => {
    let {
        username,
        password
    } = req.body;
    let file = fs.readFileSync('./data/persons.json', 'utf-8');
    file = JSON.parse(file)
    let o = file.findIndex(item => item.username == username && item.password == password);
    if (!username || !password) {
        next('账号或密码不能为空');
        return;
    }
    if (o == -1) {
        next('账号或密码输入错误');
    } else {
        res.send('登录成功');
    };


});

// router.use((err, req, res, next) => {
//     console.log(err);
//     res.status(555);
//     res.send(`<h1>${err}</h1>`);
// });

// router.use((req, res) => {
//     res.status(404);
//     let fileUrl = path.resolve(__dirname, '../views/404.html');
//     res.sendFile(fileUrl);
// });





module.exports = router;